import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import md5 from 'js-md5'
import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import { Loading, MessageBox } from 'element-ui'
import {PERMITION_DENY, AUTH_WITH_TOKEN} from './constant.js'

/* md5 */
Vue.prototype.$md5 = md5

/* Element-ui */
Vue.use(Element, { size: 'mini' })

/* axios */
import Axios from 'axios'
Axios.defaults.baseURL = process.env.NODE_ENV === 'production' 
  ? 'http://centos202/bb'
  : 'http://127.0.0.1:8088/bb'

Axios.defaults.withCredentials = true
Vue.prototype.$axios = Axios
let loadingInstance

Axios.interceptors.request.use(function(config){
  /* 显示遮罩 */
  loadingInstance = Loading.service({
    lock: true,
    text: 'Loading',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  /* 登录外的其他请求 */
  if (config.url !== '/login') {
    let loginUser = localStorage.getItem('loginUser')

    /* 未登录而访问后台，路由到登录页面 */
    if (loginUser === null) {
      MessageBox.alert('您还未登录，请重新登录。', '提示')
      router.push('/login')
    } else {
      /* 配置的登录验证为token */
      if (AUTH_WITH_TOKEN) {
        let token = localStorage.getItem('token')
        if (token === null) {
          MessageBox.alert('您还未登录，请重新登录。', '提示')
          router.push('/login')
        } else {
          config.headers.common["Authorization"] = token
        }
      }
    }
  }

	return config;
});

Axios.interceptors.response.use(response => {  
  /* 隐藏遮罩 */
  loadingInstance.close()

  if (AUTH_WITH_TOKEN) {
    let token = response.headers['authorization']
    if (token) {
      localStorage.setItem('token', token)
    }
  }

	return response
}, 
error => {
  /* 隐藏遮罩 */
  loadingInstance.close()

  if (!error.response) {
    MessageBox.alert('网络异常', '错误')
  } else if (error.response.status) {
    if (error.response.status === PERMITION_DENY){
      MessageBox.alert(error.response.data.data, '提示')
      router.push('/login')
    }	else {      
      MessageBox.alert(error, '错误')
    }
  }

  return Promise.reject(error)
})

Vue.config.productionTip = false

/* 注册v-focus指令，自动获得焦点 */
Vue.directive('focus', {
  inserted (el, binding, vnode) {    
    el.querySelector('input').focus()
  }
})

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
